package com.prone.vyuan.widget.dpdialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.dongdongsongcan.app.R;

/**
 * 自定义Dialog
 * 
 * @author Prone
 */
public class CustomDialog extends Dialog {

	public CustomDialog(Context context, int theme) {
		super(context, theme);
	}

	public CustomDialog(Context context) {
		super(context);
	}

	/**
	 * Helper class for creating a custom dialog
	 */
	public static class Builder {

		// 上下文
		private Context mContext;

		// 标题栏文字
		private String mTitle;

		// 消息内容文字
		private String mMessage;

		// 确定按钮显示文字
		private String mPositiveButtonText;

		// 取消按钮显示文字
		private String mNegativeButtonText;

		// 扩展按钮显示文字，位于确认取消按钮中间
		private String mExpendButtonText;

		// 消息内容
		private View mContentView;

		// dialog item adapter
		private ItemsAdapter mItemsAdapter;

		// 标题栏icon
		private int mIconResId = 0;// R.drawable.ic_dialog_info;

		private DialogInterface.OnClickListener mPositiveButtonClickListener,
				mNegativeButtonClickListener, mExpendButtonClickListener;

		public Builder(Context context) {
			this.mContext = context;
		}

		/**
		 * Set the Dialog message from String
		 * 
		 * @param mTitle
		 * @return
		 */
		public Builder setMessage(String message) {
			this.mMessage = message;
			return this;
		}

		/**
		 * Set the Dialog message from resource
		 * 
		 * @param mTitle
		 * @return
		 */
		public Builder setMessage(int message) {
			this.mMessage = (String) mContext.getText(message);
			return this;
		}

		/**
		 * Set the Dialog title from resource
		 * 
		 * @param title
		 * @return
		 */
		public Builder setTitle(int title) {
			this.mTitle = (String) mContext.getText(title);
			return this;
		}

		/**
		 * Set the Dialog title from String
		 * 
		 * @param title
		 * @return
		 */
		public Builder setTitle(String title) {
			this.mTitle = title;
			return this;
		}

		/**
		 * 设置dialog标题栏图标
		 * 
		 * @param iconResId
		 *            标题栏图标
		 * @return
		 */
		public Builder setTitleIcon(int iconResId) {
			this.mIconResId = iconResId;
			return this;
		}

		/**
		 * Set a custom content view for the Dialog. If a message is set, the
		 * contentView is not added to the Dialog...
		 * 
		 * @param v
		 * @return
		 */
		public Builder setContentView(View v) {
			this.mContentView = v;
			return this;
		}

		/**
		 * Set the positive button resource and it's listener
		 * 
		 * @param positiveButtonText
		 * @param listener
		 * @return
		 */
		public Builder setPositiveButton(int positiveButtonText,
				DialogInterface.OnClickListener listener) {
			return setPositiveButton(
					(String) mContext.getText(positiveButtonText), listener);
		}

		/**
		 * Set the positive button text and it's listener
		 * 
		 * @param positiveButtonText
		 * @param listener
		 * @return
		 */
		public Builder setPositiveButton(String positiveButtonText,
				DialogInterface.OnClickListener listener) {
			this.mPositiveButtonText = positiveButtonText;
			this.mPositiveButtonClickListener = listener;
			return this;
		}

		/**
		 * Set the negative button resource and it's listener
		 * 
		 * @param negativeButtonText
		 * @param listener
		 * @return
		 */
		public Builder setNegativeButton(int negativeButtonText,
				DialogInterface.OnClickListener listener) {
			return setNegativeButton(
					(String) mContext.getText(negativeButtonText), listener);
		}

		/**
		 * Set the negative button text and it's listener
		 * 
		 * @param negativeButtonText
		 * @param listener
		 * @return
		 */
		public Builder setNegativeButton(String negativeButtonText,
				DialogInterface.OnClickListener listener) {
			this.mNegativeButtonText = negativeButtonText;
			this.mNegativeButtonClickListener = listener;
			return this;
		}

		/**
		 * 设置扩展按钮
		 * 
		 * @param expendButtonText
		 * @param listener
		 * @return
		 */
		public Builder setExpendButton(int expendButtonText,
				DialogInterface.OnClickListener listener) {
			return setNegativeButton(
					(String) mContext.getText(expendButtonText), listener);
		}

		/**
		 * 设置扩展按钮
		 * 
		 * @param expendButtonText
		 * @param listener
		 * @return
		 */
		public Builder setExpendButton(String expendButtonText,
				DialogInterface.OnClickListener listener) {
			this.mExpendButtonText = expendButtonText;
			this.mExpendButtonClickListener = listener;
			return this;
		}

		/**
		 * 设置单选对话框
		 * 
		 * @param items
		 *            单项项
		 * @param defaultPosition
		 *            默认选中项,-1不选中
		 * @param listener
		 *            改变监听
		 * @return
		 */
		public Builder setSingleChoiceItems(String[] items,
				int defaultPosition,
				final DialogInterface.OnClickListener listener) {
			mItemsAdapter = new ItemsAdapter(mContext, items,
					ItemsAdapter.ItemStyle.SINGLE_CHOICE, defaultPosition);
			if (defaultPosition >= 0) {
				mItemsAdapter.setChecked(defaultPosition, true);
			}
			mItemsAdapter.setDialogOnclickListener(listener);

			mContentView = LayoutInflater.from(mContext).inflate(
					R.layout.dpdialog_items_layout, null);
			ListView listView = (ListView) mContentView;
			listView.setAdapter(mItemsAdapter);

			if (defaultPosition >= 0) {
				listView.setSelection(defaultPosition);
			}

			return this;
		}

		/**
		 * 设置单选对话框
		 * 
		 * @param items
		 *            单项项
		 * @param defaultPosition
		 *            定位项，如果不定位制定-1
		 * @param listener
		 *            改变监听
		 * @return
		 */
		public Builder setItems(String[] items, int defaultPosition,
				DialogInterface.OnClickListener listener) {
			mItemsAdapter = new ItemsAdapter(mContext, items,
					ItemsAdapter.ItemStyle.ITEM, defaultPosition);
			mItemsAdapter.setDialogOnclickListener(listener);

			mContentView = LayoutInflater.from(mContext).inflate(
					R.layout.dpdialog_items_layout, null);
			ListView listView = (ListView) mContentView;
			listView.setAdapter(mItemsAdapter);
			if (defaultPosition >= 0) {
				listView.setSelection(defaultPosition);
			}
			return this;
		}

		/**
		 * 设置多选items
		 * 
		 * @param items
		 *            显示字符
		 * @param checked
		 *            是否选中状态
		 * @param listener
		 *            监听
		 * @return
		 */
		public Builder setMultiChoiceItems(String[] items, int defaultPosition,
				boolean[] checked,
				DialogInterface.OnMultiChoiceClickListener listener) {
			mItemsAdapter = new ItemsAdapter(mContext, items,
					ItemsAdapter.ItemStyle.MULTI_CHOICE, defaultPosition);
			mItemsAdapter.setDialogMultiChoiceClickListener(listener);
			if (checked != null) {
				mItemsAdapter.setChecked(checked);
			}

			mContentView = LayoutInflater.from(mContext).inflate(
					R.layout.dpdialog_items_layout, null);
			ListView listView = (ListView) mContentView;
			listView.setAdapter(mItemsAdapter);

			if (defaultPosition >= 0) {
				listView.setSelection(defaultPosition);
			}

			return this;
		}

		/**
		 * 创建Dialog
		 */
		public CustomDialog create() {

			// 初始化布局
			LayoutInflater inflater = (LayoutInflater) mContext
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final CustomDialog dialog = new CustomDialog(mContext,
					R.style.Dialog);
			dialog.setCanceledOnTouchOutside(false);
			View layout = inflater.inflate(R.layout.dpdialog_layout, null);

			// 设置参数
			WindowManager.LayoutParams windowParams = new WindowManager.LayoutParams();
			int widthPixels = mContext.getResources().getDisplayMetrics().widthPixels;
			windowParams.x = 0;
			windowParams.y = widthPixels;

			// 控制dialog停放位置
			Window window = dialog.getWindow();
			window.setAttributes(windowParams);
			window.setWindowAnimations(R.style.DialogAnimStyle);
			dialog.setCanceledOnTouchOutside(true);

			dialog.addContentView(layout, new LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

			// 最终决定dialog的大小,实际由contentView确定了
			dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
					LayoutParams.WRAP_CONTENT);

			// 设置标题栏
			TextView txtTitle = (TextView) layout.findViewById(R.id.title);
			txtTitle.setText(mTitle);

			Button btnPositive = null;
			Button btnNegative = null;
			Button btnExpend = (Button) layout.findViewById(R.id.expendButton);
			View viewPositiveDevider = null;
			View viewNegativeDevider = null;
			View viewExpendDevider = layout.findViewById(R.id.expendBtnDevider);
			viewExpendDevider.setVisibility(View.GONE);
			// 是否4.0以上版本
			boolean isVersion14 = VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH;
			// 根据不同版本，完成确认取消按钮的位置替换
			if (isVersion14) {
				viewPositiveDevider = layout
						.findViewById(R.id.negativeBtnDevider);
				viewPositiveDevider.setVisibility(View.GONE);
				btnPositive = (Button) layout.findViewById(R.id.negativeButton);
				btnNegative = (Button) layout.findViewById(R.id.positiveButton);
			} else {
				viewNegativeDevider = layout
						.findViewById(R.id.negativeBtnDevider);
				viewNegativeDevider.setVisibility(View.GONE);
				btnPositive = (Button) layout.findViewById(R.id.positiveButton);
				btnNegative = (Button) layout.findViewById(R.id.negativeButton);
			}

			if (mIconResId > 0) {
				txtTitle.setCompoundDrawablesWithIntrinsicBounds(mIconResId, 0,
						0, 0);
				txtTitle.setCompoundDrawablePadding((int) (10 * mContext
						.getResources().getDisplayMetrics().density));
			} else {
				txtTitle.setCompoundDrawablePadding(0);
			}

			// 按钮显示分割线
			if (isVersion14) {
				if (mPositiveButtonText != null
						&& (mNegativeButtonText != null || mExpendButtonText != null)) {
					viewPositiveDevider.setVisibility(View.VISIBLE);
				}

				if (mExpendButtonText != null && mNegativeButtonText != null) {
					viewExpendDevider.setVisibility(View.VISIBLE);
				}

			} else {
				if (mNegativeButtonText != null
						&& (mPositiveButtonText != null || mExpendButtonText != null)) {
					viewNegativeDevider.setVisibility(View.VISIBLE);
				}

				if (mExpendButtonText != null && mPositiveButtonText != null) {
					viewExpendDevider.setVisibility(View.VISIBLE);
				}
			}

			// 设置确定呢按钮
			if (mPositiveButtonText != null) {
				btnPositive.setText(mPositiveButtonText);
				btnPositive.setShadowLayer(0.51f, 0, -1, Color.BLACK);
				btnPositive
						.setBackgroundResource(R.drawable.dpdialog_positive_button_bg_selector);
				btnPositive.setTextColor(mContext.getResources().getColor(
						R.color.dialog_btn_positive_textColor));
				btnPositive.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						if (mPositiveButtonClickListener != null) {
							mPositiveButtonClickListener.onClick(dialog,
									DialogInterface.BUTTON_POSITIVE);
						}

						if (dialog.isShowing()) {
							dialog.dismiss();
						}
					}
				});

			} else {
				// 未设置则隐藏
				btnPositive.setVisibility(View.GONE);
			}

			// 设置取消按钮
			if (mNegativeButtonText != null) {
				btnNegative.setText(mNegativeButtonText);
				btnNegative.setShadowLayer(0.51f, 0, -1, Color.GRAY);
				btnNegative
						.setBackgroundResource(R.drawable.dpdialog_normal_button_bg_selector);
				btnNegative.setTextColor(mContext.getResources().getColor(
						R.color.dialog_btn_normal_textColor));
				btnNegative.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						if (mNegativeButtonClickListener != null) {
							mNegativeButtonClickListener.onClick(dialog,
									DialogInterface.BUTTON_NEGATIVE);
						}
						if (dialog.isShowing()) {
							dialog.dismiss();
						}
					}
				});
			} else {
				// 未设置则隐藏
				btnNegative.setVisibility(View.GONE);
			}

			// 设置扩展按钮
			if (mExpendButtonText != null) {
				btnExpend.setText(mExpendButtonText);
				btnExpend.setShadowLayer(0.51f, 0, -1, Color.GRAY);
				btnExpend
						.setBackgroundResource(R.drawable.dpdialog_normal_button_bg_selector);
				btnExpend.setTextColor(mContext.getResources().getColor(
						R.color.dialog_btn_normal_textColor));
				btnExpend.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						if (mExpendButtonClickListener != null) {
							mExpendButtonClickListener.onClick(dialog,
									DialogInterface.BUTTON_NEUTRAL);
						}
						if (dialog.isShowing()) {
							dialog.dismiss();
						}
					}
				});
			} else {
				// 未设置则隐藏
				btnExpend.setVisibility(View.GONE);
			}

			// 设置显示的消息
			if (mMessage != null) {
				TextView mTxtMessage = ((TextView) layout
						.findViewById(R.id.message));
				// mTxtMessage.setMaxHeight((int) (0.7 *
				// mContext.getResources().getDisplayMetrics().heightPixels));
				mTxtMessage.setText(mMessage);
			} else if (mContentView != null) {
				// 设置自定义内容
				((FrameLayout) layout.findViewById(R.id.content))
						.removeAllViews();
				((FrameLayout) layout.findViewById(R.id.content))
						.addView(mContentView);

				// 给列表设置dialog对象引用
				if (mItemsAdapter != null) {
					mItemsAdapter.setDialog(dialog);
				}
			}
			dialog.setContentView(layout);
			return dialog;
		}

	}

	/**
	 * 列表对话框Adapter
	 * 
	 * @author Prone
	 */
	public static class ItemsAdapter extends BaseAdapter {

		// 列表类型
		public static enum ItemStyle {
			ITEM, /* 仅有列表item */
			SINGLE_CHOICE, /* 单选 */
			MULTI_CHOICE/* 多选 */
		};

		private ItemStyle itemStyle;

		private String[] items;

		private boolean[] checked;

		private Context context;

		private int defaultPosition;

		/**
		 * 非多选单击对话框
		 */
		private DialogInterface.OnClickListener mDClickListener;

		/**
		 * 多选时间监听
		 */
		private DialogInterface.OnMultiChoiceClickListener mDMultiChoiceListener;

		private DialogInterface dialog;

		public ItemsAdapter(Context ctx, String[] items, ItemStyle itemStyle,
				int defaultPosition) {
			this.items = items;
			this.itemStyle = itemStyle;
			checked = new boolean[items.length];
			context = ctx;
			this.defaultPosition = defaultPosition;
		}

		public void setDialog(DialogInterface dialog) {
			this.dialog = dialog;
		}

		/**
		 * 非多选单击对话框
		 * 
		 * @param listener
		 */
		public void setDialogOnclickListener(
				DialogInterface.OnClickListener listener) {
			mDClickListener = listener;
		}

		/**
		 * 设置多选单机对话框
		 * 
		 * @param listener
		 */
		public void setDialogMultiChoiceClickListener(
				DialogInterface.OnMultiChoiceClickListener listener) {
			mDMultiChoiceListener = listener;
		}

		/**
		 * 设置某一项默认选中，适合SINGLE_CHOICE
		 * 
		 * @param position
		 */
		public void setChecked(int position, boolean isChecked) {
			checked[position] = isChecked;
		}

		/**
		 * 设置选中项，适合MULTI_CHOICE
		 * 
		 * @param position
		 */
		public void setChecked(boolean[] choices) {
			this.checked = choices;
		}

		public boolean isChecked(int position) {
			return checked[position];
		}

		/**
		 * 获得当前adapter的类型
		 * 
		 * @return
		 */
		public ItemStyle getItemStyle() {
			return itemStyle;
		}

		@Override
		public int getCount() {
			return items.length;
		}

		@Override
		public Object getItem(int position) {
			return items[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			Holder holder = null;
			if (convertView == null) {
				convertView = LayoutInflater.from(context).inflate(
						R.layout.dpdialog_item_layout, null);
				holder = new Holder();
				holder.mItemView = convertView
						.findViewById(R.id.layoutItemContent);
				holder.mDevider = convertView
						.findViewById(R.id.viewItemDevider);
				holder.mTxtText = (TextView) convertView
						.findViewById(R.id.txtText);
				holder.mChoiceLayout = convertView
						.findViewById(R.id.layoutChoices);
				holder.mRadioChoice = (RadioButton) convertView
						.findViewById(R.id.radioChoice);
				holder.mCheckChoice = (CheckBox) convertView
						.findViewById(R.id.checkBoxChoice);

				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}

			holder.mDevider
					.setVisibility((position == getCount() - 1) ? View.GONE
							: View.VISIBLE);

			holder.mTxtText.setText(items[position]);

			switch (itemStyle) {
			case ITEM:
				holder.mChoiceLayout.setVisibility(View.GONE);

				holder.mItemView.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						if (mDClickListener != null) {
							mDClickListener.onClick(dialog, position);
						}
						if (dialog != null) {
							dialog.dismiss();
						}
					}
				});
				break;
			case MULTI_CHOICE:
				holder.mChoiceLayout.setVisibility(View.VISIBLE);
				holder.mCheckChoice.setVisibility(View.VISIBLE);
				holder.mRadioChoice.setVisibility(View.GONE);

				holder.mCheckChoice.setChecked(checked[position]);
				holder.mCheckChoice
						.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								multiChoiceClick(position);
							}
						});

				holder.mItemView.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						multiChoiceClick(position);
					}
				});

				break;
			case SINGLE_CHOICE:
				holder.mChoiceLayout.setVisibility(View.VISIBLE);
				holder.mCheckChoice.setVisibility(View.GONE);
				holder.mRadioChoice.setVisibility(View.VISIBLE);

				holder.mRadioChoice.setChecked(checked[position]);

				holder.mRadioChoice
						.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								singleChoiceClick(position);

								if (dialog != null) {
									dialog.dismiss();
								}
							}
						});

				holder.mItemView.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						singleChoiceClick(position);

						if (dialog != null) {
							dialog.dismiss();
						}
					}
				});
				break;
			}

			convertView.setLongClickable(false);
			convertView.setClickable(false);
			convertView.setEnabled(false);
			return convertView;
		}

		private void singleChoiceClick(int position) {
			// if (!checked[position]) {
			for (int i = 0; i < checked.length; i++) {
				checked[i] = false;
			}
			checked[position] = true;
			notifyDataSetChanged();

			if (mDClickListener != null) {
				mDClickListener.onClick(dialog, position);
			}
			// }
		}

		private void multiChoiceClick(int position) {
			checked[position] = !checked[position];
			notifyDataSetChanged();
			if (mDMultiChoiceListener != null) {
				mDMultiChoiceListener.onClick(dialog, position,
						checked[position]);
			}
		}

		private static class Holder {
			View mItemView;

			View mDevider;

			TextView mTxtText;

			View mChoiceLayout;

			CheckBox mCheckChoice;

			RadioButton mRadioChoice;
		}

	}

}
